package com.lm.scau.dyb.db.Dalx;

import android.content.ContentValues;
import android.database.Cursor;

import com.lm.scau.dyb.activity.base.BaseActivity;
import com.lm.scau.dyb.bean.Notice;
import com.lm.scau.dyb.db.DybDB;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2016/8/20.
 */
public class NoticeDalx extends BaseDalx{
    private static final String TB_NAME = "tb_notice";
    private static final String NT_ID = "nt_id";
    private static final String NT_TITLE = "nt_title";
    private static final String NT_INFO = "nt_info";
    private static final String NT_TIME = "nt_time";

    public NoticeDalx(BaseActivity activity) {
        if (db == null) {
            db = DybDB.get(activity);
        }
        if (!db.tabbleIsExist(TB_NAME)) {
            createDataFileTable();
        }
    }
    private void createDataFileTable() {
        String createTableSql = "CREATE TABLE IF NOT EXISTS " + TB_NAME + "(" + NT_ID
                + " varchar, " + NT_TITLE + " varchar, " + NT_INFO + " varchar, " + NT_TIME + " varchar)";
        db.creatTable(createTableSql);
    }
    /**
     * 获取最新的轮播时间，用来更新最新数据
     *
     * @return
     */
    @Override
    public String getLatelyTime() {
        String sql = "select " + NT_TIME + " from " + TB_NAME +
                " order by " + NT_TIME + " desc limit ?";
        Cursor cursor = db.find(sql, new String[]{"1"});
        String time = "1970-01-01 00:00:00";

        while (cursor.moveToNext()) {
            time = cursor.getString(cursor.getColumnIndex(NT_TIME));
            break;
        }
        return time;
    }

    /**
     * 新增轮播数据
     *
     * @param notice
     * @return
     */
    public boolean addNotices(Notice notice) {
        boolean isOk = false;
        ContentValues values = new ContentValues();
        values.put(NT_ID, notice.getNoticeID());
        values.put(NT_TITLE, notice.getNoticeTitle());
        values.put(NT_INFO, notice.getNoticeInfo());
        values.put(NT_TIME, notice.getNoticeTime());
        if (db.save(TB_NAME, values)) {
            isOk = true;
        }
        return isOk;
    }

    public List<Notice> getNotices(){
        String sql = "select *"  + " from " + TB_NAME +
                " order by " + NT_TIME + " desc limit ?";
        Cursor cursor = db.find(sql, new String[]{"10000"});
        List<Notice> list = new ArrayList<>();
        while (cursor.moveToNext()) {
            Notice notice = new Notice();
            notice.setNoticeInfo(cursor.getString(cursor.getColumnIndex(NT_INFO)));
            notice.setNoticeTime(cursor.getString(cursor.getColumnIndex(NT_TIME)));
            notice.setNoticeTitle(cursor.getString(cursor.getColumnIndex(NT_TITLE)));
            list.add(notice);
        }
        return list;
    }
}
